<template>

  <div id="app" class="container">

    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item >文档问答助手</el-breadcrumb-item>

      </el-breadcrumb>
    </div>
    <el-row :gutter="20" class="row-gutter">
      <el-col :span="12" class="doc-column">
        <!-- 下拉选择框，用于选择文件 -->
        <div class="selected">
        <el-select v-model="selectedFileId" placeholder="请选择文件" style="width: 458px">
          <el-option
            v-for="item in fileData"
            :key="item.id"
            :label="item.fileName"
            :value="item.id">
          </el-option>
        </el-select>
        </div>
        <div class="scrollable-shadow-box">
          <el-scrollbar style="height: 420px;">
            <div v-html="computedSelectedFile ? computedSelectedFile.content : ''"></div>
          </el-scrollbar>
        </div>
      </el-col>
      <el-col :span="12">

        <div class="title-bar">AI问答</div>
        <div id="chat-window" class="chat-window" >
          <div id="ChatGPT-response" ref="responseText" class="chat-log" >
            <div
              v-for="(message, index) in chatLog"
              :key="index"
              :class="{'user-message': message.startsWith('👤:'), 'ai-message': message.startsWith('🤖:')}"
            >
              {{ message }}
            </div>
          </div>
        </div>
        <div id="chat-input" class="chat-input">
          <el-input
            v-model="inputText"
            id="chat-gpt-input"

            placeholder="输入问题"
            clearable
          ></el-input>

          <el-button :loading="isLoading" size="small" type="primary"  @click="callCHATGPT">发送</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
  import axios from "axios";

  export default {
    data() {
      return {
        isLoading:false,
        data1:'',
        inputText: '',
        chatLog: [],
        fileData:[],
        content:[],
        // 请求数据参数
        formInline: {
          page: 1,
          limit: 10,
          fileName: '',
          isLock: ''
        },
        selectedFileId:null, // 用于存储当前选中的文件的id

      };
    },
   created() {
      this.data1 = localStorage.getItem('userId')
      this.getUnStructSourceData();

    },
    computed: {
      // 创建一个计算属性来返回选中的文件
      computedSelectedFile() {
        return this.fileData.find(file => file.id === this.selectedFileId);
      },
    },
    watch: {
      selectedFileId(newVal, oldVal) {
        if (newVal !== oldVal && newVal !== null) {
          // 当selectedFileId发生变化并且不为null时，清空chatLog
          this.chatLog = [];
          // 如果需要，可以在这里调用callCHATGPT方法
          // this.callCHATGPT();
        }
      }
    },
    methods: {
      async callCHATGPT() {
        if(this.selectedFileId!=null){
         this.content =  this.fileData.find(file => file.id === this.selectedFileId).content;

          const userInput = this.inputText; // 存储用户输入到临时变量
          this.chatLog.push("👤:" + userInput); // 使用临时变量添加到日志中
          this.inputText = ''; // 清空 inputText
          const prompt1 = this.content+'\n'+userInput ; // 使用临时变量作为 prompt 的值
          this.isLoading = true; // 开始时设置加载状态
          const url = this.$global.javaUrl + "/indicatorConfig/chat";
          const userId = localStorage.getItem('userId');
          const config = {
            headers: {
              'user': userId
            },

          };
          axios.post(url,{prompt:prompt1}, config)
            .then(response => {
              this.resData = response.data.data;
              console.log(this.resData)
              this.chatLog.push('🤖:' + this.resData);
              this.isLoading = false; // 请求失败，结束加载状态
            })
            .catch(error => {
              this.isLoading = false; // 请求失败，结束加载状态
              console.error('请求失败：', error);
              this.showError('请求失败，请稍后再试！');

            });



        }else {
          this.$message.error('请先选择文件！')
        }

      },
      // 计算属性，根据selectedFileId找到对应的文件对象

      getUnStructSourceData(){
        this.logining = true
        this.fileData = []
        let url = this.$global.javaUrl+"/dataSource/listUnStruct"
        let config = {
          headers:
            {
              //'Content-Type':'application/json',
              'user' : localStorage.getItem('userId')
            },
          params: {
            pageNum: this.formInline.page,
            pageSize:1000,
            tagId:0

          }
        }

        axios.get(url, config).then(response=>{
          this.UnStructSourceData = response.data.data.rows

          // 以格式化的方式显示对象内容
          for(var i = 0; i < this.UnStructSourceData.length; i++) {
            this.fileData.push({
              id: this.UnStructSourceData[i].id,
              fileName: this.UnStructSourceData[i].fileName,
              content: this.UnStructSourceData[i].content
            });
          }


        })

      },

      selectedFile() {
        console.log(this.selectedFileId);
        return this.fileData.find(file => file.id === this.selectedFileId);
      },
    },
  };
</script>

<style scoped>
  .breadcrumb{
    margin-bottom: 10px; /* 可选：添加底部外边距，以便与其他元素分隔 */
  }

  .title-bar {
    background-color: #bd1919; /* 蓝色背景 */
    color: white; /* 白色文字 */
    padding: 10px; /* 内边距 */
    text-align: center; /* 文字居中 */

  }
  .scrollable-shadow-box {
    border: 1px solid #dcdfe6; /* 边框样式 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    padding: 25px;
  }
  .chat-window {
    display: flex;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    flex-direction: column-reverse; /* 显示最新的消息在最上面 */
    height: 420px; /* 可以根据需要调整 */
    overflow-y: auto; /* 超出部分滚动显示 */
    padding: 10px;
    background-color: #f5f7fa;
    border: 1px solid #ccc;
    margin-bottom: 15px;

  }

  .chat-log {
    display: flex;
    flex-direction: column;
    width: 100%;

  }

  .user-message {
    align-self: flex-end; /* 用户消息靠右 */
    margin-right: 10px;
    background-color: #53bef1;
    padding: 5px 10px;
    border-radius: 5px 5px 5px 0;
    max-width: 70%; /* 可以根据需要调整 */
    margin-bottom: 10px;
  }

  .ai-message {
    align-self: flex-start; /* AI消息靠左 */
    margin-left: 10px;
    background-color: #e0f2f1;
    padding: 5px 10px;
    border-radius: 5px 5px 0 5px;
    max-width: 70%; /* 可以根据需要调整 */
    margin-bottom: 10px;
  }
  .chat-input {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
  }

  .chat-input .el-input {
    flex: 1; /* 输入框占据剩余空间 */
  }

  .chat-input .el-button {
    margin-left: 10px; /* 与输入框保持一定距离 */
  }
</style>
